package org.maiyoframework.assist.webservice.interceptor;

import java.util.List;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * WebService 权限拦截器 
 * 通过PhaseInterceptor，可以指定拦截器在哪个阶段起作用
 * 
 * @author maiYo
 * 
 */
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

	public AuthInterceptor() {
		super(Phase.PRE_INVOKE);// 该拦截器会在调用之前拦截SOAP消息
	}

	// handleMessage方法中的形参就是被拦截到的SOAP消息
	public void handleMessage(SoapMessage msg) throws Fault {
		System.out.println("AuthInterceptor Checking...");
		// 解析SOAP消息
		List<Header> headers = msg.getHeaders();
		if (headers == null || headers.size() < 1) {
			throw new Fault(new IllegalArgumentException("No Header"));
		}
		// 加入要求第一个Header带有用户名密码信息
		Header firstHeader = headers.get(0);
		Element element = (Element) firstHeader.getObject();
		NodeList usernameNode = element.getElementsByTagName("username");
		NodeList passwordNode = element.getElementsByTagName("password");
		// 检查验证信息是否合符要求规范，用户名密码只能出现一次
		if (usernameNode.getLength() != 1 || passwordNode.getLength() != 1) {
			throw new Fault(new IllegalArgumentException("Error Format"));
		}
		String username = usernameNode.item(0).getTextContent();
		String password = passwordNode.item(0).getTextContent();
		if ("maiyo".equals(username) && "123321".equals(password))
			System.out.println("Passport verified");
		else
			throw new Fault(new IllegalArgumentException(
					"Wrong username or password"));
	}

}
